import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { showToast } from 'vant'
import api from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref(null)
  const token = ref(getToken())
  const permissions = ref([])
  const roles = ref([])
  const loginLoading = ref(false)
  const userProfile = ref({
    avatar: '',
    nickname: '',
    email: '',
    phone: '',
    gender: '',
    birthday: '',
    location: '',
    bio: '',
    preferences: {
      theme: 'auto',
      language: 'zh-CN',
      notifications: {
        course: true,
        exam: true,
        system: true,
        email: false,
        sms: false
      }
    }
  })
  
  // 学习统计
  const learningStats = ref({
    totalCourses: 0,
    completedCourses: 0,
    totalExams: 0,
    passedExams: 0,
    totalStudyTime: 0,
    currentStreak: 0,
    longestStreak: 0,
    points: 0,
    level: 1,
    certificates: []
  })

  // 计算属性
  const isLoggedIn = computed(() => !!token.value && !!user.value)
  const isAdmin = computed(() => roles.value.includes('admin'))
  const isTeacher = computed(() => roles.value.includes('teacher'))
  const isStudent = computed(() => roles.value.includes('student'))
  const hasPermission = computed(() => (permission) => permissions.value.includes(permission))
  const completionRate = computed(() => {
    if (learningStats.value.totalCourses === 0) return 0
    return Math.round((learningStats.value.completedCourses / learningStats.value.totalCourses) * 100)
  })
  const passRate = computed(() => {
    if (learningStats.value.totalExams === 0) return 0
    return Math.round((learningStats.value.passedExams / learningStats.value.totalExams) * 100)
  })

  // 方法
  const setUser = (userData) => {
    user.value = userData
    if (userData) {
      roles.value = userData.roles || []
      permissions.value = userData.permissions || []
    }
  }

  const setUserProfile = (profileData) => {
    userProfile.value = { ...userProfile.value, ...profileData }
  }

  const setLearningStats = (statsData) => {
    learningStats.value = { ...learningStats.value, ...statsData }
  }

  // 登录
  const login = async (credentials) => {
    try {
      loginLoading.value = true
      const response = await api.auth.login(credentials)
      const { token: newToken, user: userData } = response.data
      
      // 保存token
      token.value = newToken
      setToken(newToken)
      
      // 设置用户信息
      setUser(userData)
      
      // 获取用户详细信息
      await getUserInfo()
      
      showToast('登录成功')
      return response
    } catch (error) {
      console.error('登录失败:', error)
      showToast(error.message || '登录失败')
      throw error
    } finally {
      loginLoading.value = false
    }
  }

  // 注册
  const register = async (userData) => {
    try {
      const response = await api.auth.register(userData)
      showToast('注册成功，请登录')
      return response
    } catch (error) {
      console.error('注册失败:', error)
      showToast(error.message || '注册失败')
      throw error
    }
  }

  // 登出
  const logout = async () => {
    try {
      if (token.value) {
        await api.auth.logout()
      }
    } catch (error) {
      console.error('登出请求失败:', error)
    } finally {
      // 清除本地数据
      token.value = null
      user.value = null
      permissions.value = []
      roles.value = []
      userProfile.value = {
        avatar: '',
        nickname: '',
        email: '',
        phone: '',
        gender: '',
        birthday: '',
        location: '',
        bio: '',
        preferences: {
          theme: 'auto',
          language: 'zh-CN',
          notifications: {
            course: true,
            exam: true,
            system: true,
            email: false,
            sms: false
          }
        }
      }
      learningStats.value = {
        totalCourses: 0,
        completedCourses: 0,
        totalExams: 0,
        passedExams: 0,
        totalStudyTime: 0,
        currentStreak: 0,
        longestStreak: 0,
        points: 0,
        level: 1,
        certificates: []
      }
      
      removeToken()
      showToast('已退出登录')
      
      // 跳转到登录页
      router.push({ name: 'Login' })
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      if (!token.value) return null
      
      const response = await api.auth.getUserInfo()
      const userData = response.data
      
      setUser(userData)
      setUserProfile(userData.profile || {})
      
      return userData
    } catch (error) {
      console.error('获取用户信息失败:', error)
      // 如果token无效，清除登录状态
      if (error.status === 401) {
        await logout()
      }
      throw error
    }
  }

  // 更新用户资料
  const updateProfile = async (profileData) => {
    try {
      const response = await api.user.updateProfile(profileData)
      setUserProfile(response.data)
      showToast('资料更新成功')
      return response
    } catch (error) {
      console.error('更新资料失败:', error)
      showToast(error.message || '更新失败')
      throw error
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    try {
      const response = await api.user.changePassword(passwordData)
      showToast('密码修改成功')
      return response
    } catch (error) {
      console.error('修改密码失败:', error)
      showToast(error.message || '修改密码失败')
      throw error
    }
  }

  // 上传头像
  const uploadAvatar = async (file) => {
    try {
      const formData = new FormData()
      formData.append('avatar', file)
      
      const response = await api.user.uploadAvatar(formData)
      const avatarUrl = response.data.url
      
      // 更新用户头像
      userProfile.value.avatar = avatarUrl
      if (user.value) {
        user.value.avatar = avatarUrl
      }
      
      showToast('头像上传成功')
      return response
    } catch (error) {
      console.error('头像上传失败:', error)
      showToast(error.message || '头像上传失败')
      throw error
    }
  }

  // 获取学习统计
  const getLearningStats = async () => {
    try {
      const response = await api.user.getLearningStats()
      setLearningStats(response.data)
      return response.data
    } catch (error) {
      console.error('获取学习统计失败:', error)
      throw error
    }
  }

  // 更新用户偏好设置
  const updatePreferences = async (preferences) => {
    try {
      const response = await api.user.updatePreferences(preferences)
      userProfile.value.preferences = { ...userProfile.value.preferences, ...preferences }
      showToast('设置已保存')
      return response
    } catch (error) {
      console.error('更新偏好设置失败:', error)
      showToast(error.message || '设置保存失败')
      throw error
    }
  }

  // 忘记密码
  const forgotPassword = async (email) => {
    try {
      const response = await api.auth.forgotPassword({ email })
      showToast('重置邮件已发送')
      return response
    } catch (error) {
      console.error('发送重置邮件失败:', error)
      showToast(error.message || '发送失败')
      throw error
    }
  }

  // 重置密码
  const resetPassword = async (resetData) => {
    try {
      const response = await api.auth.resetPassword(resetData)
      showToast('密码重置成功')
      return response
    } catch (error) {
      console.error('重置密码失败:', error)
      showToast(error.message || '重置失败')
      throw error
    }
  }

  // 刷新token
  const refreshToken = async () => {
    try {
      const response = await api.auth.refreshToken()
      const newToken = response.data.token
      
      token.value = newToken
      setToken(newToken)
      
      return newToken
    } catch (error) {
      console.error('刷新token失败:', error)
      await logout()
      throw error
    }
  }

  // 检查认证状态
  const checkAuthStatus = async () => {
    try {
      if (!token.value) return false
      
      await getUserInfo()
      return true
    } catch (error) {
      console.error('检查认证状态失败:', error)
      return false
    }
  }

  // 初始化认证
  const initAuth = async () => {
    try {
      if (token.value) {
        await getUserInfo()
        await getLearningStats()
      }
    } catch (error) {
      console.error('初始化认证失败:', error)
      // 如果初始化失败，清除token
      await logout()
    }
  }

  // 绑定第三方账号
  const bindThirdParty = async (provider, code) => {
    try {
      const response = await api.user.bindThirdParty({ provider, code })
      showToast('绑定成功')
      return response
    } catch (error) {
      console.error('绑定第三方账号失败:', error)
      showToast(error.message || '绑定失败')
      throw error
    }
  }

  // 解绑第三方账号
  const unbindThirdParty = async (provider) => {
    try {
      const response = await api.user.unbindThirdParty({ provider })
      showToast('解绑成功')
      return response
    } catch (error) {
      console.error('解绑第三方账号失败:', error)
      showToast(error.message || '解绑失败')
      throw error
    }
  }

  return {
    // 状态
    user,
    token,
    permissions,
    roles,
    loginLoading,
    userProfile,
    learningStats,
    
    // 计算属性
    isLoggedIn,
    isAdmin,
    isTeacher,
    isStudent,
    hasPermission,
    completionRate,
    passRate,
    
    // 方法
    setUser,
    setUserProfile,
    setLearningStats,
    login,
    register,
    logout,
    getUserInfo,
    updateProfile,
    changePassword,
    uploadAvatar,
    getLearningStats,
    updatePreferences,
    forgotPassword,
    resetPassword,
    refreshToken,
    checkAuthStatus,
    initAuth,
    bindThirdParty,
    unbindThirdParty
  }
})